//
//  QRCodeUtils.swift
//  MasterBoy
//
//  Created by kyson on 2024/8/29.
//

import Foundation


class QRCodeUtils: NSObject {
    
    static func pictureQRCodeResult(image : UIImage!) -> String? {
        
        guard let ciimg = CIImage(image: image) else {
            return nil
        }
        let detector = CIDetector(ofType: CIDetectorTypeQRCode,
                                  context: nil,
                                  options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
        guard let features = detector?.features(in: ciimg) else {
            return nil
        }
        guard let feature = features.first(where: { $0.type == CIFeatureTypeQRCode }) as? CIQRCodeFeature else {
            return nil
        }
        return feature.messageString // 识别结果
        
    }
    
    static func qrcodeWithUrl(groupUrl: String!) -> UIImage? {
        let filter = CIFilter.init(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        
        let data = groupUrl.data(using: .utf8)
        
        filter?.setValue(data, forKeyPath: "inputMessage")

        let outputImage = filter?.outputImage

        if let outputImage = outputImage {
            return createUIImageFromCIImage(image: outputImage, size: 100)
        }
        return nil
    }
    
    private static func createUIImageFromCIImage(image: CIImage, size: CGFloat) -> UIImage {
      let extent = image.extent.integral
      let scale = min(size / extent.width, size / extent.height)
      
      /// Create bitmap
      let width = size_t(extent.width * scale)
      let height = size_t(extent.height * scale)
      let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
      let bitmap = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 1)
      
      let context = CIContext.init()
      let bitmapImage = context.createCGImage(image, from: extent)
      if let bitmap = bitmap, let bitmapImage = bitmapImage {
        bitmap.interpolationQuality = .none
        bitmap.scaleBy(x: scale, y: scale)
        bitmap.draw(bitmapImage, in: extent)
        if let scaledImage = bitmap.makeImage() {
          return UIImage.init(cgImage: scaledImage)
        }
      }
      return UIImage()
    }
}
